package com.example.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.user.dto.LoginDto;
import com.example.model.user.pojo.User;
import com.example.user.mapper.UserMapper;
import com.example.user.service.UserService;
import com.example.utils.common.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl< UserMapper, User > implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(LoginDto loginDto) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(loginDto.getUserPhone()) && StringUtils.isNotEmpty(loginDto.getPassword())) {
            // 根据手机号查询用户信息
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserPhone, loginDto.getUserPhone());
            User user = userMapper.selectOne(wrapper);
            if (user == null) {
                R.error(ResultCodeRecord.AP_USER_DATA_NOT_EXIST, "管理员不存在");
            }
            // 获取加盐
            // 将输入密码进行加盐加密
            String password = loginDto.getPassword() + user.getUserSalt();
            // 输入密码加盐后MD5密码
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            // 比较密码是否相同
            if (!md5Password.equals(user.getPassword())) {
                R.error(ResultCodeRecord.AP_USER_DATA_NOT_EXIST, "密码错误");
            }
            //去掉敏感数据
            user.setPassword(null);
            user.setUserSalt(null);
            map.put("user", user);
            map.put("token", JwtUtil.getToken(user.getUserId().longValue()));
            return map;
        } else {
            // 游客登录
            map.put("token", JwtUtil.getToken(0L));
            return map;
        }
    }
}
